package com.vonchenchen.usbmuxd_android.usbmuxd.client;

import android.content.Context;
import android.util.Log;

import com.vonchenchen.usbmuxd_android.usbmuxd.Config;
import com.vonchenchen.usbmuxd_android.usbmuxd.localconn.ILocalConnector;
import com.vonchenchen.usbmuxd_android.usbmuxd.localconn.socket.SocketConnector;
import com.vonchenchen.usbmuxd_android.usbmuxd.localconn.socket.SocketReciver;
import com.vonchenchen.usbmuxd_android.usbmuxd.muxdprotocol.protocol.UsbmuxdProtocol;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 本地数据接收端
 * Created by lidechen on 3/24/17.
 */

public abstract class LocalClient implements ILocalClient{

    private final static String TAG = "LocalClient";

    private Thread mClientThread;

    protected Context mContext;

    private ILocalConnector mILocalConnector;

    protected InputStream mUSBCameraInputStream;
    protected OutputStream mUSBCameraOutputStream;

    public LocalClient(Context context, int port, int recvCacheSize, int sendCacheSize){

        mContext = context;
        initCameraService(port, recvCacheSize, sendCacheSize);
    }

    private void initCameraService(final int port, final int recvCacheSize, final int sendCacheSize){

            mClientThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //mServerSocket = null;
                    mILocalConnector = null;

                    byte[] buffer = new byte[UsbmuxdProtocol.USB_MTU];

                    try {

                        mILocalConnector = new SocketReciver("127.0.0.1", port);
                        mILocalConnector.setReceiveBufferSize(recvCacheSize);
                        mILocalConnector.open();

                        while (true) {

                            int len = 0;
                            if(Config.DEBUG) {
                                Log.i(TAG, "USB Camera socket close ...");
                            }

                            ((SocketReciver)mILocalConnector).accept();

                            if(Config.DEBUG) {
                                Log.i(TAG, "USB Camera socket established ...");
                            }

                            mUSBCameraOutputStream = mILocalConnector.getOutputStream();
                            mUSBCameraInputStream = mILocalConnector.getInputStream();

                            while ((len = mUSBCameraInputStream.read(buffer)) != -1) {

                                if(Config.DEBUG) {
                                    Log.i(TAG, "HardwareSocket USB Camera socket receive ..." + len);
                                }

                                if (mSocketDataReceiveListener != null) {
                                    mSocketDataReceiveListener.onRecive(buffer, len);
                                }
                            }
                        }

                    } catch (IOException e) {
//                    e.printStackTrace();

                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
            mClientThread.start();
        }


    private SocketDataReceiveListener mSocketDataReceiveListener;

    public void setSocketDataBack(SocketDataReceiveListener socketDataReceiveListener) {
        mSocketDataReceiveListener = socketDataReceiveListener;
    }

    public interface SocketDataReceiveListener {
         void onRecive(byte[] data, int lenght);
    }

    @Override
    public int send(byte[] data) {

        if (mUSBCameraOutputStream == null) {
            if(Config.DEBUG) {
                Log.i(TAG, "USB Camera socket send failed ...");
            }
            return -1;
        }

        try {
            mUSBCameraOutputStream.write(data);
            mUSBCameraOutputStream.flush();
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

/*    private boolean mIsConnected = false;
    private ConnStatusReceiver mConnStatusReceiver;

    public void registConnStatusReceiver() {
        mConnStatusReceiver = new ConnStatusReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SimpleTcpWrapper.TCP_CONN_STATUS_CHANGE);
        mContext.registerReceiver(mConnStatusReceiver, filter);
    }

    public void unregistConnStatusReceiver() {
        mContext.unregisterReceiver(mConnStatusReceiver);
    }

    protected class ConnStatusReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int state = intent.getIntExtra("USBHeartBeatState", TcpProtocol.TCP_DISCONNECTED);

            if (state == MyProtocol.TCP_CONNECTED) {
                if (mSocketDataReceiveListener != null) {
                    mSocketDataReceiveListener.onConnect();
                }
                mIsConnected = true;
            } else {
                mIsConnected = false;
                Log.i("USBHeartBeatStatefalse", "" + state);
                if (mSocketDataReceiveListener != null) {
                    mSocketDataReceiveListener.onClose();
                }
            }

//            if (mOnConnStatusChangedListener != null) {
//                mOnConnStatusChangedListener.onStatusChange(sIsConnected);
//            }

            Log.i(TAG, "USBHeartBeatState " + state);
        }
    }*/

}
